import re

import pymongo
import requests
from bson import ObjectId

import delete_repeat_movie
from database.db import get_invalid_movie, set_movie_online_verified, movieCol, videoCol


def check_link(link):
    try:
        resp = requests.get(link, headers={
            'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Mobile Safari/537.36'},
                            timeout=30, verify=False)
        site = re.findall('(http[s]?://.*?)/', link)[0]
        m3u8 = site + re.findall(r'([_0-9a-z/A-Z]+\.m3u8)', resp.text)[0]
        try:
            mp4 = site + re.findall(r'([_0-9a-z/A-Z]+\.mp4)', resp.text)[0]
        except:
            mp4 = ''
        try:
            pic = site + re.findall(r'pic = "([_0-9a-z/.A-Z]+)"', resp.text)[0]
        except:
            pic = ''
        print(m3u8)
        return True, (m3u8, mp4, pic)
    except Exception as e:
        raise e
        return False, None


def check():
    while movie := get_invalid_movie():
        online = movie['online']
        verified = []
        print(movie['title'], end='\t')
        for item in online:
            link = item['video_link']
            valid, source = check_link(link)
            if valid:
                item['source'] = source
                verified.append(item)
                print(item['title'], '有效')
            else:
                print(item['title'], '无效')
        set_movie_online_verified(movie, verified, 1 if verified else -1)


def deleteRepeat():
    movies = []
    skip = 0
    while True:
        ret = []
        cursor = movieCol.find({}, {'_id': 1, 'title': 1}).limit(100).skip(skip * 100)
        for c in cursor:
            ret.append(dict(c))
        if ret:
            movies += ret
            skip += 1
        else:
            break
    for i in range(len(movies) - 1):
        m = movies[i]
        title = m['title']
        print('检查', m)
        for j in range(i + 1, len(movies)):
            otherMovie = movies[j]
            if title == otherMovie['title']:
                try:
                    movieCol.delete_one(otherMovie)
                    print('删除', otherMovie)
                except:
                    pass


def check():
    movies = []
    skip = 0
    while True:
        ret = []
        cursor = movieCol.find({'valid': 0}, {'_id': 1, 'title': 1, 'name': 1}).sort('date', pymongo.DESCENDING).limit(100).skip(skip * 100)
        for c in cursor:
            ret.append(dict(c))
        if ret:
            movies += ret
            skip += 1
        else:
            break
    for m in movies:
        name = m['name']
        print(name)
        cursor = videoCol.find({'movie': name})
        for c in cursor:
            c = dict(c)
            movie_id = c['movie_id']
            if not movieCol.find_one({'_id': ObjectId(movie_id)}, {'name': 1}):
                videoCol.update(c, {'$set': {'movie_id': str(m['_id'])}})
                movieCol.update(m, {'$set': {'valid': 1}})
                print(name, c['_id'])


if __name__ == '__main__':
    check()
